//
//  DiscoverBasicViewController.m
//  JPWords
//
//  Created by 梁淑婷 on 2024/6/17.
//

#import "DiscoverBasicViewController.h"
#import "BasicClassListCell.h"
#import <PDFKit/PDFKit.h>
#import "DiscoverTopView.h"
#import "DiscoverBasicCateManager.h"
#import "DiscoverBasicCateModel.h"
#import "DiscoverBasicCateListManager.h"
#import "DiscoverBasicCateListModel.h"
#import "LoginViewController.h"

@interface DiscoverBasicViewController ()<UITableViewDelegate,UITableViewDataSource,JPAPIManagerCallBackDelegate>

@property(nonatomic,strong)UITableView *leftTableView;
@property(nonatomic,strong)NSMutableArray *cateArr;
@property(nonatomic,assign)NSInteger sel_index;
@property (nonatomic,strong)PDFView *pdfView;
@property(nonatomic,strong)DiscoverTopView *topView;
@property(nonatomic,strong)DiscoverBasicCateManager *cateManager;
@property(nonatomic,strong)DiscoverBasicCateListManager *cateListManager;
@property(nonatomic,assign)NSInteger cate_index;//子分类下标
@property(nonatomic,strong)NSMutableArray *cateListArr;
@property(nonatomic,assign)CGFloat w80;
@property(nonatomic,assign)BOOL isup;

@end

@implementation DiscoverBasicViewController

-(NSMutableArray *)cateArr{
    if(!_cateArr){
        _cateArr = [NSMutableArray array];
    }
    return _cateArr;
}

-(DiscoverBasicCateManager *)cateManager{
    if(!_cateManager){
        _cateManager = [[DiscoverBasicCateManager alloc]init];
        _cateManager.delegate = self;
    }
    return _cateManager;
}

-(DiscoverBasicCateListManager *)cateListManager{
    if(!_cateListManager){
        _cateListManager = [[DiscoverBasicCateListManager alloc]init];
        _cateListManager.delegate = self;
    }
    return _cateListManager;
}

-(NSMutableArray *)cateListArr{
    if(!_cateListArr){
        _cateListArr = [NSMutableArray array];
    }
    return _cateListArr;
}

-(void)viewDidLoad{
    [super viewDidLoad];
    
    self.sel_index = 0;
    self.cate_index = 0;
    self.isup = NO;
    [self createUI];
    [self loadCateData];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(loginSuccess:) name:@"loginSuccess" object:nil];
        
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(logoutSuccess) name:@"logoutSuccess" object:nil];
   
}

#pragma mark - 登录过期
-(void)needLogin{
    if([[self currentViewController] isKindOfClass:[DiscoverBasicViewController class]]){
        [self refreshUI];
    }
}

#pragma mark - 登录成功
-(void)loginSuccess:(NSNotification*)notifi{
    [self refreshUI];
}

#pragma mark - 退出登录成功
-(void)logoutSuccess{
    [self refreshUI];
}

#pragma mark - 刷新界面
-(void)refreshUI{
    self.sel_index = 0;
    self.cate_index = 0;
    if(self.cateArr.count > 0){
        [self.leftTableView reloadData];
        if(self.sel_index < self.cateArr.count){
            DiscoverBasicCateModel *model = self.cateArr[self.sel_index];
            self.topView.name = model.dictDataName;
        }
        if(self.cateListArr.count > 0){
            self.topView.sel_index = self.cate_index;
            self.topView.arr = self.cateListArr;
            [self loadPDF];
        }else{
            [self loadCateListData];
        }
    }else{
        [self loadCateData];
    }
}

#pragma mark - 获取分类数据
-(void)loadCateData{
    [self.cateManager loadData];
}

#pragma mark - 获取分类子列表数据
-(void)loadCateListData{
    if(self.sel_index < self.cateArr.count){
        DiscoverBasicCateModel *model = self.cateArr[self.sel_index];
        self.cateListManager.dictId = model.dictDataId;
        [self.cateListManager loadData];
    }
}

-(void)createUI{
    
    self.customNavigationBar.backgroundColor = [UIColor clearColor];
    self.customNavigationBar.hidden = YES;
    self.view.backgroundColor = [UIColor whiteColor];
    self.w80 = [DeviceUtils getAdaptedWidthForDesignWidth:80 andCurrentAvailableWidth:self.currentAvailableWidth];
    self.leftTableView = [[UITableView alloc]initWithFrame:CGRectMake(0,0,self.w80,self.currentAvailableHeight-kYM_NAVIGATIONBAR_HEIGHT-kYM_TABBAR_HEIGHT) style:UITableViewStyleGrouped];
    self.leftTableView.delegate = self;
    self.leftTableView.dataSource = self;
    self.leftTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.leftTableView.rowHeight = 54;
    self.leftTableView.backgroundColor = KbgColor;
    [self.leftTableView registerClass:NSClassFromString(@"BasicClassListCell") forCellReuseIdentifier:@"BasicClassListCell"];
    self.leftTableView.showsVerticalScrollIndicator = NO;
    self.leftTableView.bounces = NO;
    [self.view addSubview:self.leftTableView];
    UIView *footerView = [[UIView alloc]initWithFrame:CGRectMake(0,0,self.w80,kBottomJGH)];
    footerView.backgroundColor = KbgColor;
    self.leftTableView.tableFooterView = footerView;
    
    // 创建PDFView实例
    self.pdfView = [[PDFView alloc]initWithFrame:CGRectMake(self.w80+12,49, self.currentAvailableWidth-self.w80-24,self.currentAvailableHeight-kYM_NAVIGATIONBAR_HEIGHT-kYM_TABBAR_HEIGHT-49)];
    self.pdfView.backgroundColor = [UIColor whiteColor];
    self.pdfView.pageShadowsEnabled = NO;
    [self.view addSubview:self.pdfView];
    
    
    self.topView = [[DiscoverTopView alloc]initWithFrame:CGRectMake(self.w80,0,self.currentAvailableWidth-self.w80,49) andCurrentAvailableWidth:self.currentAvailableWidth];
    self.topView.currentAvailableWidth = self.currentAvailableWidth;
    [self.view addSubview:self.topView];
    __weak typeof(self)self_weak_ = self;
    [self.topView setUpdownBlock:^(BOOL isUp) {
        self_weak_.isup = isUp;
        if(isUp == YES){
            self_weak_.topView.frame = CGRectMake(self_weak_.w80,0,self_weak_.currentAvailableWidth-self_weak_.w80,self_weak_.currentAvailableHeight-kYM_NAVIGATIONBAR_HEIGHT-kYM_TABBAR_HEIGHT);
        }else{
            self_weak_.topView.frame = CGRectMake(self_weak_.w80,0,self_weak_.currentAvailableWidth-self_weak_.w80,49);
        }
    }];
    [self.topView setClickBlock:^(NSInteger index) {
        NSString *userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
        if(userId){
//            NSString *loginMode = [[NSUserDefaults standardUserDefaults]objectForKey:@"loginMode"];
//            if(loginMode&&[loginMode isEqualToString:@"4"]){
//                //游客需要登录
//                [self_weak_ login];
//            }else{
                if(self_weak_.topView.upDownBtn.selected == YES){
                    [self_weak_.topView refreshDownUI];
                }
                self_weak_.cate_index = index;
                [self_weak_ loadPDF];
//            }
        }else{
            [self_weak_ login];
        }
    }];
    
}

#pragma mark - 屏幕宽度改变
- (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator {
    [super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
    if(isIPAD){
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            // 获取当前可用宽度并更新布局
            self.currentAvailableWidth = [DeviceUtils currentAvailableWidth];
            self.currentAvailableHeight = [DeviceUtils currentAvailableHeight];
            self.customNavigationBar.frame = CGRectMake(0,0,self.currentAvailableWidth,kYM_NAVIGATIONBAR_HEIGHT);
            self.w80 = [DeviceUtils getAdaptedWidthForDesignWidth:80 andCurrentAvailableWidth:self.currentAvailableWidth];
            self.leftTableView.frame = CGRectMake(0,0,self.w80,self.currentAvailableHeight-kYM_NAVIGATIONBAR_HEIGHT-kYM_TABBAR_HEIGHT);
            [self.leftTableView reloadData];
            self.pdfView.frame = CGRectMake(self.w80+12,49, self.currentAvailableWidth-self.w80-24,self.currentAvailableHeight-kYM_NAVIGATIONBAR_HEIGHT-kYM_TABBAR_HEIGHT-49);
            [self adjustPDFViewHeight];
            if(self.isup == YES){
                self.topView.frame = CGRectMake(self.w80,0,self.currentAvailableWidth-self.w80,self.currentAvailableHeight-kYM_NAVIGATIONBAR_HEIGHT-kYM_TABBAR_HEIGHT);
            }else{
                self.topView.frame = CGRectMake(self.w80,0,self.currentAvailableWidth-self.w80,49);
            }
            self.topView.currentAvailableWidth = self.currentAvailableWidth;
            [self.topView refreshWidth];
            
        });
    }
}


#pragma mark - 登录
-(void)login{
    LoginViewController *vc = [[LoginViewController alloc]init];
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - 加载pdf文件
-(void)loadPDF{
    if(self.cate_index < self.cateListArr.count){
        self.pdfView.hidden = YES;
        DiscoverBasicCateListModel *model = self.cateListArr[self.cate_index];
        NSURL *pdfURL = [NSURL URLWithString:model.path];
        PDFDocument *pdfDocument = [[PDFDocument alloc] initWithURL:pdfURL];
        self.pdfView.document = pdfDocument;
        self.pdfView.autoScales = YES;
        // 调整 PDFView 的高度
        [self adjustPDFViewHeight];
        // 延迟显示 PDFView
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.25 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            self.pdfView.hidden = NO;
        });
    }else{
        self.pdfView.hidden = YES;
    }
}

#pragma mark - 调整 PDFView 的高度
- (void)adjustPDFViewHeight {
    if (self.pdfView.document) {
        // 获取PDF文档的页数
        NSUInteger pageCount = self.pdfView.document.pageCount;
        CGFloat totalHeight = 0.0;

        // 遍历每一页，计算总高度
        for (NSUInteger i = 0; i < pageCount; i++) {
            PDFPage *page = [self.pdfView.document pageAtIndex:i];
            CGRect pageRect = [page boundsForBox:kPDFDisplayBoxMediaBox];

            // 计算当前页的缩放比例和高度
            CGFloat scale = self.pdfView.bounds.size.width / pageRect.size.width;
            CGFloat pageHeight = pageRect.size.height * scale;

            // 累加所有页面的高度
            totalHeight += pageHeight;
        }

        // 限制总高度不超过屏幕可用高度
        CGFloat maxHeight = self.currentAvailableHeight - kYM_NAVIGATIONBAR_HEIGHT - kYM_TABBAR_HEIGHT - 49;
        CGFloat finalHeight = MIN(totalHeight, maxHeight);

        // 设置PDFView的高度
        CGRect pdfViewFrame = self.pdfView.frame;
        pdfViewFrame.size.height = finalHeight;
        self.pdfView.frame = pdfViewFrame;

        // 设置显示模式
        self.pdfView.autoScales = YES;
        self.pdfView.displayMode = kPDFDisplaySinglePageContinuous;
        self.pdfView.displayDirection = kPDFDisplayDirectionVertical;

        // 确保第一页显示在顶部
        [self.pdfView goToPage:[self.pdfView.document pageAtIndex:0]];
    }
}


#pragma mark - tableview
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    BasicClassListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"BasicClassListCell"];
    if(indexPath.section < self.cateArr.count){
        DiscoverBasicCateModel *model = self.cateArr[indexPath.section];
        cell.title = model.dictDataName;
    }
    if(indexPath.section == _sel_index){
        cell.isSel = YES;
    }else{
        cell.isSel = NO;
    }
    return cell;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.cateArr.count;;
}

-(UIView*)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView *footerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0,self.w80,10)];
    UIView *bgView = [[UIView alloc]initWithFrame:CGRectMake(0,0,self.w80,20)];
    [footerView addSubview:bgView];
    if(section == _sel_index){
        footerView.backgroundColor = [UIColor whiteColor];
        bgView.backgroundColor = KbgColor;
        [bgView addRoundedCorners:UIRectCornerTopRight withRadii:CGSizeMake(10, 10)];
    }else{
        if((_sel_index > 0)&&(section == _sel_index-1)){
            bgView.frame = CGRectMake(0,-10,self.w80,20);
            footerView.backgroundColor = [UIColor whiteColor];
            bgView.backgroundColor = KbgColor;
            [bgView addRoundedCorners:UIRectCornerBottomRight withRadii:CGSizeMake(10,10)];
        }else{
            footerView.backgroundColor = KbgColor;
            bgView.backgroundColor = KbgColor;
            [bgView addRoundedCorners:UIRectCornerAllCorners withRadii:CGSizeMake(0,0)];
        }
    }
    footerView.clipsToBounds = YES;
    return footerView;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 10.0;
}

-(UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *headerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.w80,0.00001)];
    headerView.backgroundColor = KbgColor;
    return headerView;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.00001;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSString *userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
    if(userId){
//        NSString *loginMode = [[NSUserDefaults standardUserDefaults]objectForKey:@"loginMode"];
//        if(loginMode&&[loginMode isEqualToString:@"4"]){
//            //游客需要登录
//            [self login];
//        }else{
            self.sel_index = indexPath.section;
            [self.leftTableView reloadData];
            if(self.sel_index < self.cateArr.count){
                DiscoverBasicCateModel *model = self.cateArr[self.sel_index];
                self.topView.name = model.dictDataName;
            }
            if(self.topView.upDownBtn.selected == YES){
                [self.topView refreshDownUI];
            }
            [self.cateListArr removeAllObjects];
            self.cate_index = 0;
            [self loadCateListData];
//        }
    }else{
        [self login];
    }
    
}

#pragma mark - JPAPIManagerCallBackDelegate
-(void)managerCallDLDLAPIDidSuccess:(JPAPIBaseManager *)manager{
    
    if([manager isEqual:self.cateManager]){
        NSDictionary *dic = manager.response.content;
        NSArray *arr = [DiscoverBasicCateModel mj_objectArrayWithKeyValuesArray:dic[@"data"]];
        self.cateArr = [NSMutableArray arrayWithArray:arr];
        [self.leftTableView reloadData];
        if(self.sel_index < self.cateArr.count){
            DiscoverBasicCateModel *model = self.cateArr[self.sel_index];
            self.topView.name = model.dictDataName;
        }
        [self loadCateListData];
    }
    
    if([manager isEqual:self.cateListManager]){
        NSDictionary *dic = manager.response.content;
        NSArray *arr = [DiscoverBasicCateListModel mj_objectArrayWithKeyValuesArray:dic[@"data"]];
        self.cateListArr = [NSMutableArray arrayWithArray:arr];
        self.topView.sel_index = self.cate_index;
        self.topView.arr = self.cateListArr;
        [self loadPDF];
    }
}

-(void)managerCallDLDLAPIDidFailed:(JPAPIBaseManager *)manager{
    if(manager.errorMessage){
        [JPProgressHUD showMsg:manager.errorMessage];
    }
}


@end
